import React from 'react';
import { V } from './containers';
import {
  Animated,
  ColorValue,
  LayoutChangeEvent,
  LayoutRectangle,
} from 'react-native';
import { TContainerProps } from './Types';

export interface TSkeletonProps extends TContainerProps {
  /**
   * Loading color
   * default is #E4E4E4
   */
  lc?: ColorValue;
  /**
   * Highlight Color when loading animated.
   * default is #FFF
   */
  //   hlc?: ColorValue;
  /**
   * Skeleton animation actived if loading=true
   */
  loading: boolean;
  /**
   * Border radius
   */
  br?: number;
  /**
   * Opacity
   */
  op?: number;
  /**
   * onLayout event
   */
  onLayout?: (event: LayoutChangeEvent) => void;
}

export function Skeleton(props: TSkeletonProps) {
  const { lc = '#E4E4E4', br = 8 } = props;
  const [layout, setLayout] = React.useState<LayoutRectangle>();
  const onLayout = (evt: LayoutChangeEvent) => {
    setLayout(evt.nativeEvent.layout);
    props.onLayout?.(evt);
  };
  return (
    <>
      <V {...props} onLayout={onLayout} op={props.loading ? 0 : props.op} />
      {props.loading && layout && (
        <V
          op={op}
          bg={lc}
          br={br}
          w={layout.width}
          h={layout.height}
          pos={[layout.y, layout.x]}
        />
      )}
    </>
  );
}

const op = new Animated.Value(0.4);
let skeletonAnimation: Animated.CompositeAnimation | null;

Skeleton.start = () => {
  skeletonAnimation?.stop?.();
  skeletonAnimation = Animated.loop(
    Animated.sequence([
      Animated.timing(op, { toValue: 1, duration: 800, useNativeDriver: true }),
      Animated.timing(op, {
        toValue: 0.4,
        duration: 800,
        useNativeDriver: true,
      }),
    ])
  );
  skeletonAnimation.start();
};

Skeleton.stop = () => {
  skeletonAnimation?.stop?.();
  skeletonAnimation = null;
};

Skeleton.op = op;
